#include "io_context_pool.h"

IOContextPool::IOContextPool(std::size_t size)
:_io_contexts(size)
,_works(size)
,_threads(size)
,_next(0)
,_thread_count(size)
{
    for(std::size_t i = 0; i < size; ++i)
    {
        _works[i] = WorkPtr(new Work(_io_contexts[i]));
        _threads.emplace_back([this, i](){
            _io_contexts[i].run();
        });
    }
}

IOContextPool::~IOContextPool()
{
    stop();
}

void IOContextPool::stop()
{
    for(auto& w: _works)
    {
        w.reset();
    }
    for(auto& t: _threads)
    {
        t.join();
    }
}

IOContextPool::IOContext& IOContextPool::get_io_context()
{
    _next %= _thread_count;
    return _io_contexts[_next++];
}